package com.ruoyi.web.controller.ToolController;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.web.controller.common.UrlCommon;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(tags = "视频相关")
@Controller
@ResponseBody
@RequestMapping("/tool/movies")
public class MoviesController extends BaseController {
    private static final String douyingString = "https?://[a-zA-Z0-9./]+";
    private static String mvRegex = "id=(\\d+)";

    @GetMapping("video/remove/watermark")
    @ApiOperation("抖音去水印--弃用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "连接地址")
    })
    public R<String> videoRemoveWatermark(@RequestParam String url) {
        Pattern pattern = Pattern.compile(douyingString);
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            String douyinUrl = matcher.group();
            String s = HttpUtil.get(UrlCommon.DOUYINGURL + "?url=" + douyinUrl);
            String videoUrl = (String) JSONObject.parseObject(JSONObject.parseObject(s).get("data").toString()).get("url");
            return R.ok(videoUrl); // 返回实际结果，而不是 null
        } else {
            return R.fail("未找到匹配项。"); // 返回适当的错误信息或处理逻辑
        }
    }

    @GetMapping("video/analysis")
    @ApiOperation("多平台短视频解析")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "连接地址")
    })
    //连接地址: https://api.aa1.cn/doc/alalysis.html
    public R<String> analysis(@RequestParam String url) {
        Pattern pattern = Pattern.compile(douyingString);
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            String douyinUrl = matcher.group();
            String s = HttpUtil.get(UrlCommon.ANALYSIS + "?url=" + douyinUrl);
            Object o = JSONObject.parseObject(s).get("data");
            return R.ok(o.toString()); // 返回实际结果，而不是 null
        } else {
            return R.fail("未找到匹配项。"); // 返回适当的错误信息或处理逻辑
        }
    }

    @GetMapping("video/wy/mv")
    @ApiOperation("网易云 mv 获取,只支持安卓手机")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "连接地址")
    })
    //连接地址:https://api.aa1.cn/doc/ncm_mv.html
    public R<String> wyMvVideo(@RequestParam String url) {
        if (!url.contains("mv")) {
            return R.fail("视频链接不是 mv 请检查");
        }
        // 编译正则表达式
        Pattern pattern = Pattern.compile(mvRegex);
        // 创建 Matcher 对象
        Matcher matcher = pattern.matcher(url);
        // 查找匹配
        if (matcher.find()) {
            // 提取匹配到的值
            String s = HttpUtil.get(UrlCommon.WY_MV_VIDEO + "?vid=" + matcher.group(1) + "&raw=false&no_cache=false");
            // 输出提取的结果
            return R.ok(s);
        } else {
            return R.fail("未找到匹配的 userid 值");
        }
    }

    @GetMapping("video/xiaojiejie")
    @ApiOperation("获取小姐姐短视频")
    //连接地址:https://api.aa1.cn/doc/ncm_mv.html
    public R<String> xiaojiejie() {
        // 提取匹配到的值
        String s = HttpUtil.get(UrlCommon.XIAO_JIAO_JIAO);
        String url = "https:"+JSONObject.parseObject(s).get("mp4");
        // 输出提取的结果
        return R.ok(url);
    }

    @GetMapping("/video/image/compression")
    @ApiOperation("压缩图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片"),
            @ApiImplicitParam(name = "quality", value = "图片质量 0-1 的浮点数,越高质量越好")
    })
    public void imageCompression(@RequestParam("file") MultipartFile file,@RequestParam Double quality) {
        String targetImagePath = "/Users/chenshuzhi/Downloads/compressed_image.jpg";
        int targetSize = 1024; // 目标压缩大小（单位：KB）
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            // 使用Thumbnailator进行图片压缩
            Thumbnails.of(inputStream)
                    .size(targetSize, targetSize)
                    .outputQuality(quality) // 设置图片质量，范围为0.0到1.0
                    .toFile(new File(targetImagePath));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }



}
